<?php
//рус
include_once (_CORE_PATH . "system_loader.php");
include_once (_CORE_PATH . "router/router_factory.php");

include_once (_APP_PATH . "match_media_status.php");

final class CoreController
{
    /**
		сам объект Фронт Контроллера
     */
    private static $instance;
    static public function GetInstance ()
    {
        if (! (self::$instance instanceof self)) self::$instance = new self();
        return self::$instance;
    }
    private function __construct ()
    {
        //set timezone
        SysLoader::GetLibCollection()->date->SetTimeZone(MozgCfg::GetProp('global//timeZone'));
    }
    /**
		устанавливаем нужный протокол
     */
    private function GetProtocol ()
    {
        if ($_SERVER['DOCUMENT_ROOT']) 
        {
            return 'http';
        } 
        else 
        {
            return 'std';
        }
    }
    /**
		устанавливаем нужный постфикс
     */
    private function GetEnv($protocol)
    {
        $_request = SysLoader::GetRequest($protocol);
        if ('http' == $protocol) 
        {
            if ($_request->isXmlHttpRequest() || $_request->has('ajax')) 
            {
                return '_ajax';
            } 
            else 
            {
                return '_web';
            }
        } 
        else 
        {
            return '_cli';
        }
    }
    
    /**
		запуск
	*/
    public function Run ()
    {   
        $protocol = $this->GetProtocol();
        
		$env = $this->GetEnv($protocol);
		list($moduleName, $ctrlName, $actionName) = MozgRoute::Get($protocol)->GetActiveRoute();			

		$moduleCollection = SysLoader::GetModuleCollection();
		if (!strlen($moduleName) || !$moduleCollection->IsModuleExists($moduleName, $protocol, $env))
		{
			die('Module not found ' .$moduleName);
		}
		
		$module = SysLoader::GetModule($moduleName, $protocol, $env);
		$module->Auth();

		if ((false !== $ctrlName) && !strlen($ctrlName)) $ctrlName = 'default';
		
		if ((false === $ctrlName) 
			|| (false === $actionName)
			|| !isset($module->GetCtrlCollection()->$ctrlName)
			|| !$module->GetCtrlCollection()->$ctrlName->ActionExists($actionName. 'Pr'))
		{
			$ctrlName = 'errors';
			$actionName = 'NotFound';	
		}
		
		$actionName .= 'Pr';

		$module->GetCtrlCollection()->$ctrlName->$actionName();

		$module->GetDecorator()->Run();
        $module->GetResponse()->SendResponse();
    }
}